package com.fxd.serviceorder.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.fxd.model.order.bean.Order;
import com.fxd.serviceorder.config.OrderProperties;
import com.fxd.serviceorder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xudongfu
 * @date 2025/06/08
 */
// nacos配置自动刷新
@Slf4j
@RefreshScope
@RestController
//@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Value("${order.timeout}")
    private String timeout;

    @Autowired
    private OrderProperties orderProperties;

    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {

        return orderService.createOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallBack")
    public Order seckill(@RequestParam(value = "userId", required = false) Long userId,
                         @RequestParam(value = "productId", defaultValue = "1000") Long productId) {

        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallBack(Long userId,
                                 Long productId,
                                 Throwable throwable) {
        Order order = new Order();
        order.setId(Long.MAX_VALUE);
        order.setNickName("seckillFallBack");
        order.setAddress(throwable.getClass().toString());
        return order;
    }

    @GetMapping("/config")
    public String config() {

        return timeout;
    }

    @GetMapping("/config2")
    public OrderProperties config2() {
        return orderProperties;
    }

    @GetMapping("/writeDb")
    public String writeDb() {
        return "writeDb success";
    }

    @GetMapping("/readDb")
    public String readDb() {
        log.info("readDb");
        return "readDb success";
    }

}
